/**
 * 发送get请求
 * @param {string} url 请求地址
 * @param {object} params   请求参数
 * @param {string} type     返回的接口数据
 * @param {object} headers  自定义请求头
 * @returns promise
 */

function get(url, params, headers = {}, datatype = 'json') {
    // 定义空数组
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    let res = xhr.responseText
                    switch (datatype) {
                        case 'json':
                            res = JSON.parse(res)
                            break;
                        default:
                            break;
                    }
                    resolve(res)
                }
                else {
                    reject(xhr.status)
                }
            }
        }
        let tempArr = []
        for (let key in params) {
            tempArr.push(`${key}=${params[key]}`)
        }
        //设置请求方式、请求地址
        xhr.open('get', `${url}?${tempArr.join('&')}`)
        for (let key in headers) {
            xhr.setRequestHeader(key, headers[key])
        }
        xhr.send(null)
    })
}
/**
* 发送get请求
* @param {string} url 请求地址
* @param {object} params   请求参数
* @param {string} type     返回的接口数据
* @param {object} headers  自定义请求头
* @returns promise
*/

function post(url, params = {}, headers = {}, datatype = 'json') {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    let res = xhr.responseText
                    switch (datatype) {
                        case 'json':
                            res = JSON.parse(res)
                            break;
                        default:
                            break;
                    }
                    resolve(res)
                } else {
                    reject(xhr.status)
                }
            }
        }
        xhr.open('post', url)
        xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
        for (let key in headers) {
            xhr.setRequestHeader(key, headers[key])
        }
        let tempArr = []
        for (let key in params) {
            tempArr.push(`${key}=${params[key]}`)
        }
        xhr.send(tempArr.join('&'))
    })
}